const fs = require('fs')
const path = require('path')

const arguments = process.argv.splice(2)

const file = arguments[0]

if (!fs.existsSync(file)) {
    console.log('file not exists')
    return
}

const data = fs.readFileSync(file, 'utf-8')
if (!data) {
    console.log('file is empty')
    return
}

const lines = data.split('\n')
const new_lines = []
const temp = {}
for (let i = 0, length = lines.length; i < length; i++) {
    const line = lines[i].trim()
    if (temp[line] !== true) {
        temp[line] = true
        new_lines.push(line)
    }
}
new_lines.sort()

const dir = path.dirname(file)
const name = path.basename(file)
const ext = path.extname(file)
const new_file = path.join(dir, name + '_sort' + ext)
const new_data = new_lines.join('\n')
fs.writeFileSync(new_file, new_data)